package cn.toys.modular.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import cn.toys.base.auth.annotion.Permission;
import cn.toys.base.consts.ConstantsContext;
import cn.toys.base.pojo.page.LayuiPageFactory;
import cn.toys.modular.result.ProductResult;
import cn.toys.modular.warpper.ProductWrapper;
import cn.toys.sys.core.exception.enums.BizExceptionEnum;
import cn.toys.sys.modular.system.entity.FileInfo;
import cn.toys.sys.modular.system.enums.FileTypeEnum;
import cn.toys.sys.modular.system.enums.UploadTypeEnum;
import cn.toys.sys.modular.system.model.UploadResult;
import cn.toys.sys.modular.system.service.FileInfoService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import cn.toys.sys.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import cn.toys.modular.entity.Product;
import cn.toys.modular.service.IProductService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 产品管理控制器
 *
 * @author fengshuonan
 * @Date 2021-02-26 23:58:24
 */
@Controller
@RequestMapping("/product")
public class ProductController extends BaseController {

    private String PREFIX = "/modular/product/";

    @Autowired
    private IProductService productService;
    @Autowired
    private FileInfoService fileInfoService;

    /**
     * 跳转到产品管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "product.html";
    }

    /**
     * 跳转到添加产品管理
     */
    @RequestMapping("/product_add")
    public String productAdd() {
        return PREFIX + "product_add.html";
    }

    /**
     * 跳转到修改产品管理
     */
    @RequestMapping("/product_edit")
    public String productUpdate(@RequestParam String productId) {
        Product product = this.productService.getById(productId);
        LogObjectHolder.me().set(product);
        return PREFIX + "product_edit.html";
    }

    /**
     * 跳转到产品图片上传
     */
    @RequestMapping("/product_upload")
    public String productUpload(@RequestParam String productId) {
        Product product = this.productService.getById(productId);
        LogObjectHolder.me().set(product);
        return PREFIX + "product_upload.html";
    }

    /**
     * 获取产品管理列表
     */
//    @Permission
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        Page<Map<String, Object>> products = this.productService.selectProducts(condition);
        Page<Map<String, Object>> wrap = new ProductWrapper(products).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }

    /**
     * 新增产品管理
     */

    @Permission
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Product product) {
        productService.save(product);
        return ResponseData.success();
    }

    /**
     * 删除产品管理
     */
    @Permission
    @RequestMapping(value = "/remove/{productId}")
    @ResponseBody
    @Transactional
    public Object delete(@PathVariable("productId") String productId) {
        productService.removeById(productId);
        //删除图片
        fileInfoService.removeByProductIds(productId);
        return ResponseData.success();
    }

    /**
     * 修改产品管理
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Object update(Product product) {
        productService.updateById(product);
        return ResponseData.success();
    }

    /**
     * 产品管理详情
     */
//    @Permission
    @RequestMapping(value = "/view/{productId}")
    @ResponseBody
    public Object detail(@PathVariable("productId") String productId) {
        if (ToolUtil.isEmpty(productId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Product prodcut = this.productService.getById(productId);
        //查找出所有的文件信息
        List<FileInfo> fileInfos = fileInfoService.selectByProductId(productId);
        ProductResult productResult = new ProductResult();
        BeanUtil.copyProperties(prodcut, productResult);
        productResult.setFileInfos(fileInfos);

        Map<String, Object> productMap = BeanUtil.beanToMap(productResult);
        return ResponseData.success(productMap);
    }

    /**
     * 产品图片上传
     *
     * @param productId
     * @param type
     * @param file
     * @return
     */
//    @Permission
    @RequestMapping(value = "/upload/{type}/{productId}")
    @ResponseBody
    public Object upload(@PathVariable(value = "productId") String productId,Integer sort, @PathVariable("type") Integer type, @RequestParam("file") MultipartFile file) {
        if (ToolUtil.isEmpty(productId) || ToolUtil.isEmpty(type)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Product product = this.productService.getById(productId);
        if (ObjectUtil.isNull(product)) {
            return ResponseData.error("没有该产品");
        }


        UploadResult uploadResult;
        if (UploadTypeEnum.LOCAL.ordinal() == type) {
            //todo 先做上传图片 , 后面系统集成阿里云
            uploadResult = this.fileInfoService.uploadFile(file, productId, sort, FileTypeEnum.IMG, UploadTypeEnum.LOCAL);
        } else {
            throw new ServiceException(BizExceptionEnum.UPLOAD_TYPE_ERROR);
        }
        //取出文件流给前端
//        UeditorUtil.readFile(uploadResult.getFinalName(),response,UeditorUtil.FileType.IMG,uploadResult.getOriginalFilename());
        //取出文件路径给前端
        String finalName = uploadResult.getFinalName();
        String[] strs;
        if (ConstantsContext.isOsWindows()) {
            strs = ConstantsContext.getFileUploadPath().split(File.separator + File.separator);
        } else {
            strs = ConstantsContext.getFileUploadPath().split(File.separator);

        }
        uploadResult.setFileSavePath("../" + strs[strs.length - 1] + "/" + finalName);


        return ResponseData.success(uploadResult);
    }


    /**
     * 产品图片删除
     */
//    @Permission
    @RequestMapping(value = "/photo/delete/{type}/{fileId}")
    @ResponseBody
    public Object photoDelete(@PathVariable("fileId") String fileId, @PathVariable("type") Integer type) {
        if (ToolUtil.isEmpty(fileId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        FileInfo fileInfo = this.fileInfoService.getById(fileId);
        if (ObjectUtil.isNull(fileInfo)) {
            return ResponseData.error("图片已被销毁");
        }
        if (UploadTypeEnum.LOCAL.ordinal() == type) {
            //todo 先做上传图片 , 后面系统集成阿里云
            this.fileInfoService.deleteFile(fileId, FileTypeEnum.IMG, UploadTypeEnum.LOCAL);
        } else {
            throw new ServiceException(BizExceptionEnum.UPLOAD_TYPE_ERROR);
        }
        this.fileInfoService.removeById(fileId);
        return ResponseData.success("删除图片成功");
    }

    /**
     * 产品图片修改
     */
//    @Permission
    @RequestMapping(value = "/photo/edit/{type}/{productId}/{sort}/{fileId}")
    @ResponseBody
    public Object photoEdit(@PathVariable("productId") String productId, @PathVariable("fileId") String fileId, @PathVariable("sort") Integer sort, @PathVariable("type") Integer type,MultipartFile file) {
        if (ToolUtil.isEmpty(fileId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        UploadResult uploadResult;
        if (UploadTypeEnum.LOCAL.ordinal() == type) {
            this.fileInfoService.deleteFile(fileId, FileTypeEnum.IMG, UploadTypeEnum.LOCAL);
             uploadResult = this.fileInfoService.uploadFile(file, productId, sort, FileTypeEnum.IMG, UploadTypeEnum.LOCAL);
        } else {
            throw new ServiceException(BizExceptionEnum.UPLOAD_TYPE_ERROR);
        }
        return ResponseData.success(uploadResult);
    }
}
